import React, { useState, useEffect } from 'react';
import useStore from '../../components/useStore';
import { 
  Table, 
  Input, 
  Button, 
  Space, 
  Form, 
  Pagination, 
  Card, 
  Typography,
  Spin,
  message,
  notification,
  Modal  // 补充导入Modal组件
} from 'antd';
import { 
  SearchOutlined, 
  ReloadOutlined, 
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined
} from '@ant-design/icons';
import request from '../../untils/request';

const Bom = () => {
  const { collapsed, setnowroute } = useStore();
  const [form] = Form.useForm();
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [bomList, setBomList] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);

  // 表格列定义
  const columns = [
    {
      title: '序号',
      key: 'index',
      render: (_text, _record, index) => {
        return (currentPage - 1) * pageSize + index + 1;
      },
      width: 80,
    },
    {
      title: '产品编号',
      key: 'number',
      render: (_text, record) => {
        return record.number;
      },
    },
    {
      title: '产品品名',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: '产品规格',
      dataIndex: 'specificationAndModel',
      key: 'specificationAndModel',
    },
    {
      title: '操作',
      key: 'action',
      render: (_text, record) => (
        <Space size="middle">
          <Button onClick={() => check(record)} icon={<EyeOutlined />} size="small" type="text">查看</Button>
          <Button onClick={() => edit(record)} icon={<EditOutlined />} size="small" type="text">编辑</Button>
          <Button onClick={() => del(record)} icon={<DeleteOutlined />} size="small" type="text" danger>删除</Button>
        </Space>
      ),
    },
  ];

  // 查看详情
  const check = (record) => {
    const detailRoute = `/ship/framework/bom/bomDetail?number=${record.number}`;
    setnowroute({
      route: detailRoute,
      title: "BOM详情"
    });
  }

  // 编辑
  const edit = (_record) => {
    notification.open({
      message:"功能正在开发中~"
    })
  }

  // 删除
  const del = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除料号为 ${record.number} 的物料吗？此操作不可撤销。`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        request("/admin/bom/deleteBom", {
          method: "POST",
          body: {
            number: record.number
          }
        }).then((res) => {
          if (res.code === 200) {
            message.success('物料删除成功');
            reloadBomList(); // 使用重新加载函数
          } else {
            message.error(`删除失败: ${res.msg || '未知错误'}`);
          }
        }).catch((error) => {
          message.error(`请求失败: ${error.message || '网络错误'}`);
        });
      }
    });
  }

  const fetchBomList = () => {
    const offset = (currentPage - 1) * pageSize;
    const { number, productName, specificationAndModel } = form.getFieldsValue();
    
    setLoading(true);
    request("/admin/bom/getBom", {
      method: "POST",
      body: {
        pageSize,
        offset,
        number: number || '',
        productName: productName || '',
        specificationAndModel: specificationAndModel || '',
        topLevel: true    // 新增参数，表示只查询顶级BOM
      }
    }).then((res) => {
      setLoading(false);
      if (res.code === 200) {
        setBomList(res.data?.list || []);
        setTotal(res.data?.pagination?.total || 0);
      } else {
        message.error(`数据加载失败: ${res.msg || '未知错误'}`);
      }
    }).catch((error) => {
      setLoading(false);
      message.error(`请求失败: ${error.message || '网络错误'}`);
    });
  };

  // 重新加载函数 - 重置页码并刷新数据
  const reloadBomList = () => {
    setCurrentPage(1);
    fetchBomList();
  };

  useEffect(() => {
    fetchBomList();
  }, [currentPage, pageSize]);

  const handleSearch = () => {
    form.validateFields().then(() => {
      setCurrentPage(1);
      fetchBomList();
    }).catch(_info => {
      message.warning('表单验证失败，请检查输入');
    });
  };

  const handleReset = () => {
    form.resetFields();
    setCurrentPage(1);
    fetchBomList();
  };

  const handlePageChange = (page, pageSize) => {
    setCurrentPage(page);
    setPageSize(pageSize);
  };

  const handleImport = () => {
    setnowroute({ route: "/ship/framework/bom/addBomByExcel", title: "Excel导入Bom" })
  };

  return (
    <div style={{    
      height: "94%", 
      backgroundColor: '#F1F1F1',
      right: "1%",
      top: "4vh",
      overflow: "hidden",
      width: collapsed ? "94%" : "84%", 
      position: "absolute",  
      transition: "width 0.3s ease"
    }}>
      <Card style={{ height: '100%', border: 0, boxShadow: 'none' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <Typography.Title level={4} style={{ margin: 0 }}>物料管理</Typography.Title>
          <Space>
            {/* 新增重新加载按钮 */}
            <Button 
              icon={<ReloadOutlined />} 
              onClick={reloadBomList}
            >
              重新加载
            </Button>
            <Button 
              type="primary" 
              icon={<UploadOutlined />} 
              onClick={handleImport}
            >
              Excel导入
            </Button>
            <Button type="primary" onClick={() => setnowroute({
                  route: "/ship/framework/bom/addBom",
                  title: "新增bom"
                })} icon={<PlusOutlined />}>新增物料</Button>
          </Space>
        </div>

        <Form 
          form={form} 
          layout="inline" 
          onFinish={handleSearch}
          style={{ marginBottom: 16 }}
        >
          <Form.Item name="number" label="产品编号">
            <Input placeholder="请输入产品编号" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="productName" label="产品品名">
            <Input placeholder="请输入产品品名" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="specificationAndModel" label="产品规格">
            <Input placeholder="请输入产品规格" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>搜索</Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>

        <div style={{ height: 'calc(100% - 140px)', overflow: 'auto' }}>
          <Spin spinning={loading}>
            <Table
              columns={columns}
              dataSource={bomList}
              rowKey="id"
              pagination={false}
              scroll={{ y: 'calc(100% - 50px)' }}
              bordered
              locale={{ emptyText: '暂无符合条件的物料数据' }}
            />
          </Spin>
        </div>

        <div style={{ textAlign: 'right', marginTop: 16 }}>
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={total}
            onChange={handlePageChange}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条记录`}
          />
        </div>
        <div style={{ marginTop: 8, fontSize: 12, color: '#666' }}>
          如果物料已经被使用或者存在子料件时，您将无法将其删除。（但可以将其禁用，禁用功能正在开发中~）
        </div>
      </Card>
    </div>
  );
};

export default Bom;
